<template>
  <a-modal 
    v-model:visible="visible" 
    title="修改密码" 
    :width="400"
    :footer="false"
  >
    <a-form 
      :model="form" 
      :rules="rules" 
      @submit="handleSubmit"
      layout="vertical"
    >
      <a-form-item field="oldPassword" label="当前密码">
        <a-input-password 
          v-model="form.oldPassword" 
          placeholder="请输入当前密码"
          size="large"
        />
      </a-form-item>
      
      <a-form-item field="newPassword" label="新密码">
        <a-input-password 
          v-model="form.newPassword" 
          placeholder="请输入新密码"
          size="large"
        />
      </a-form-item>
      
      <a-form-item field="comfirmPassword" label="确认新密码">
        <a-input-password 
          v-model="form.comfirmPassword" 
          placeholder="请再次输入新密码"
          size="large"
        />
      </a-form-item>
      
      <a-form-item>
        <a-button 
          type="primary" 
          html-type="submit" 
          :loading="loading"
          long
          size="large"
        >
          修改密码
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/stores/user'
import { changePasswordApi } from '@/api/auth'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const userStore = useUserStore()

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loading = ref(false)
const form = reactive({
  oldPassword: '',
  newPassword: '',
  comfirmPassword: ''
})

const rules = {
  oldPassword: [
    { required: true, message: '请输入当前密码' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { minLength: 6, message: '密码长度不能少于6位' }
  ],
  comfirmPassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (value: string, cb: any) => {
        if (value !== form.newPassword) {
          cb('两次输入的密码不一致')
        } else {
          cb()
        }
      }
    }
  ]
}

const handleSubmit = async ({ values, errors }: any) => {
  if (errors) return
  
  if (!userStore.userInfo?.uid) {
    Message.error('用户信息不完整')
    return
  }
  
  loading.value = true
  try {
    const res = await changePasswordApi(userStore.userInfo.uid, values)
    if (res.code === 0) {
      Message.success('密码修改成功')
      visible.value = false
      form.oldPassword = ''
      form.newPassword = ''
      form.comfirmPassword = ''
    } else {
      Message.error(res.msg || '密码修改失败')
    }
  } catch (error: any) {
    Message.error(error.response?.data?.msg || '密码修改失败')
  } finally {
    loading.value = false
  }
}
</script>